import { GCAnalytics } from "../../GCAnalytics";
import GCGlobal from "../../GCGlobal";

const { ccclass, property, menu } = cc._decorator;

@ccclass
@menu('common/HeaderComponent')
export default class HeaderComponent extends cc.Component {

    @property(cc.Label)
    nicknameLbl: cc.Label = null;

    @property(cc.Sprite)
    iconSpr: cc.Sprite = null;

    @property(cc.Label)
    heartLbl: cc.Label = null;

    @property(cc.Node)
    heartNode: cc.Node = null;

    @property(cc.Node)
    backNode: cc.Node = null;

    @property(cc.Node)
    facebookNode: cc.Node = null;

    protected onLoad(): void {
        this.facebookNode.active = false;
    }

    initUI(name: string, hearts: number, icon: string) {
        this.nicknameLbl.string = name;
        this.heartLbl.string = hearts + '';

        if (icon && /https/.test(icon)) {

            cc.assetManager.loadRemote<cc.Texture2D>(icon, { ext: '.jpg' }, (err: Error, tex: cc.Texture2D) => {
                if (!cc.isValid(this.node)) {
                    return;
                }

                const spriteFrame = new cc.SpriteFrame();
                spriteFrame.setTexture(tex);

                this.iconSpr.spriteFrame = spriteFrame;
            });
        }
    }

    updateHearts(hearts: number) {
        this.heartLbl.string = hearts + '';
    }

    getHeartPosInWorld() {
        return this.heartNode.convertToWorldSpaceAR(cc.v2());
    }

    protected onBuyBtnClicked() {
        cc.log(`onBuyBtnClicked`);
    }

    protected onBackBtnClicked() {
        cc.log(`onBackBtnClicked`);
        GCGlobal.token = '';
        cc.director.loadScene('login');
        GCGlobal.Account = null;

        GCAnalytics.logout();
    }

    protected onFacebookBtnClicked() {
        cc.log(`onFacebookBtnClicked`);
    }
}
